package dao_sys

import (
	"wrblog-api-go/app/model"
	"wrblog-api-go/app/model/model_sys"
	"wrblog-api-go/pkg/errs"
	"wrblog-api-go/pkg/mysql"
	"wrblog-api-go/pkg/utils"
)

func GetSysPostPageList(sysPost model_sys.SelectSysPost) (sysPosts []model_sys.SysPostVo, total int64, err error) {
	db := mysql.Db().Model(&model_sys.SysPostPo{})
	if sysPost.PostName != "" {
		db = db.Where("post_name like ?", "%"+sysPost.PostName+"%")
	}
	if sysPost.PostCode != "" {
		db = db.Where("post_code like ?", "%"+sysPost.PostCode+"%")
	}
	if sysPost.Status != "" {
		db = db.Where("status = ?", sysPost.Status)
	}
	if !sysPost.StartTime.IsZero() {
		db = db.Where("create_time >= ?", sysPost.StartTime)
	}
	if !sysPost.EndTime.IsZero() {
		db = db.Where("create_time <= ?", sysPost.EndTime)
	}
	db = db.Where("deleted = '0'").Count(&total).Order("post_sort").Order("create_time desc")
	if sysPost.PageNum != nil && sysPost.PageSize != nil {
		db = db.Limit(*sysPost.PageSize).Offset((*sysPost.PageNum - 1) * *sysPost.PageSize)
	} else {
		db = db.Limit(10)
	}
	err = db.Find(&sysPosts).Error
	err = errs.ErrNotFound(err)
	return
}

func GetSysPostById(postId int) (sysPost model_sys.SysPostVo, err error) {
	db := mysql.Db().Model(&model_sys.SysPostPo{})
	err = db.Where("post_id = ? and deleted = '0'", postId).First(&sysPost).Error
	err = errs.ErrNotFound(err)
	return
}

func AddSysPost(sysPost model_sys.SysPostPo) (int, error) {
	err := mysql.Db().Create(&sysPost).Error
	return sysPost.PostId, errs.ErrNotFound(err)
}
func EditSysPost(sysPost model_sys.SysPostPo) (int64, error) {
	res := mysql.Db().Updates(&sysPost)
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func RemoveSysPost(postIds []string, uk string) (int64, error) {
	db := mysql.Db().Model(&model_sys.SysPostPo{})
	db.Where("post_id in (?)", postIds)
	res := db.Updates(&model_sys.SysPostPo{BaseEntity: model.BaseEntity{UpdateTime: utils.NewTimeNow(), UpdateBy: uk, Deleted: "1"}})
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func DeleteSysPost(postIds []string) (int64, error) {
	db := mysql.Db().Model(&model_sys.SysPostPo{})
	res := db.Delete(&model_sys.SysPostPo{}, postIds)
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}
